package com.hugoo.extra.xlsx;

import java.io.*;

/**
 * 使用本类的方法： 1、初始化 Exl xl=new Exl(file); 2、设置标题xl.setTitle("");
 * 3、设置行标题xl.addRowTitle(String[] rowTitle); 4、添加行xl.addRow(i);其中i为行号，起始值为0；
 * 5、添加单元格数据xl.createCell(列号, 数值或字符串, Exl.STYLE_NUM);其中样式有数值、字符串、标题等几种固定格式。
 * 6、包装行数据xl.packRow()，用于行单元格数据插入完成后的操作; 7、Excel包装xl.pack();，用于完成数据插入之后的操作。
 *
 * @author Hugoo.Chan
 */
public class Exl {

    public static final short STYLE_TXT = 1, STYLE_PCT = 2, STYLE_FMT = 3, STYLE_NUM = 4, STYLE_TITLE = 5;
    private File tplFile;
    private String title;
    private static final int MAX_SIZE = 999999;//设置Sheet最大记录行数 为1,000,000行记录
    private Ssw2 sw;
    private WB wb;
    private String[] rowTitle;

    public Exl(File tempFile) {
        tplFile = tempFile;
        wb = new WB();
    }

    public void addRowTitle(String[] rowTitle) {
        this.rowTitle = rowTitle;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public void addRow(int i) throws IOException {
        int r = i % MAX_SIZE + 2;//本处设计为起始值为：2
        if (r == 2) {
            if (sw != null) {
                sw.endSheet();
            }
            File tmp = File.createTempFile("sheet", ".xml");
            wb.addSheet(title + (i / MAX_SIZE + 1), tmp);
//            sw = new Ssw2(new FileWriter(tmp));
            sw = new Ssw2(new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tmp), "UTF-8"))));
            sw.beginSheet();
            buildRowTitle();
        }
        sw.insertRow(r);
    }

    public void createCell(int z, double dvl, short STYLE_NUM) throws IOException {
        sw.createCell(z, dvl, STYLE_NUM);
    }

    public void packRow() throws IOException {
        sw.endRow();
    }

    public void pack() throws FileNotFoundException, IOException {
        sw.endSheet();
        wb.pack();
        FileOutputStream os = new FileOutputStream(tplFile);
        wb.pkg(os);
    }

    public void createCell(int z, String svl, short STYLE_TXT) throws IOException {
        sw.createCell(z, svl, STYLE_TXT);
    }

    private void buildRowTitle() throws IOException {
        sw.insertRow(1);//第一行，默认为：标题行
        for (int x = 0; x < rowTitle.length; x++) {
            sw.createCell(x, rowTitle[x], Exl.STYLE_TITLE);
        }
        sw.endRow();
    }
}
